package org.firestorm.traficforecast.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.firestorm.traficforecast.utils.Constant;
import org.firestorm.traficforecast.utils.Md5;

public class UserDAO {

	public static void main(String[] args) {
		String pass = Md5.Hash("123456");
//		User admin = new User(0, pass, "admin");
//		insertUser(admin);
		User now = getUser("admin", pass);
		System.out.println(now.getPassword());
	}

	// private static void createData() {
	// DBConnection connect = new DBConnection("localhost:3306/ces", "root",
	// "123456");
	// Connection conn = connect.getConnection();
	// try {
	// PreparedStatement stmt = conn
	// .prepareStatement("CREATE TABLE user(id INTEGER not NULL AUTO_INCREMENT, username VARCHAR(255), password VARCHAR(255),  PRIMARY KEY ( id )) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci");
	// stmt.execute();
	// } catch (SQLException e) {
	// e.printStackTrace();
	// }
	// }

	public static void insertUser(User user) {
		MySQLConnect connect = new MySQLConnect();
		Connection conn = connect.getConnection();
		try {
			PreparedStatement stmt = conn
					.prepareStatement("INSERT INTO user(username, password) VALUES(?, ?)");
			stmt.setString(1, user.getUserName());
			stmt.setString(2, user.getPassword());
			stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static User getUser(String u, String p) {
		MySQLConnect connect = new MySQLConnect();
		Connection conn = connect.getConnection();

		User rule = null;
		try {
			PreparedStatement stmt = conn
					.prepareStatement("SELECT * FROM user WHERE username = ? AND password = ?");
			stmt.setString(1, u);
			stmt.setString(2, p);

			ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				String ids = rs.getString("username");
				String name = rs.getString("password");
				rule = new User(rs.getInt("id"), name, ids);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rule;
	}

	public static int checkLogin(String userName, String password) {
		if(userName == null || userName.equals("") ||password == null || password.equals("")){
			return Constant.LOGIN_USER_NULL;
		}
		User user1 = getUser(userName, password);
		if (user1 != null) {

			return Constant.LOGIN_SUCCESS;
		} else {
			return Constant.LOGIN_INVALID_USER_INFO;

		}
	}
}
